﻿using ISolutions.xRM.TechDays.Shared;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System;

namespace ISolutions.xRM.TechDays.ContactCard.Utilities
{
    public delegate void ConnectedEventHandler();

    internal static class CrmConnectionManager
    {
        private static OrganizationServiceConfiguration svcConfig;
        private static AuthenticationCredentials authCreds = new AuthenticationCredentials();

        public static OrganizationServiceProxy OrgServiceProxy { get; set; }
        private static AuthenticationCredentials AuthCreds
        {
            get { return authCreds; }
            set { authCreds = value; }
        }
        public static bool IsConnected { get; set; }

        public static event ConnectedEventHandler Connected;

        public static void Connect(AuthenticationCredentials authCreds)
        {
            AuthCreds = authCreds;

            svcConfig = ServiceConfigurationFactory
                .CreateConfiguration<IOrganizationService>
                (new Uri(StaticSettings.Uri), MetadataLoaded) as OrganizationServiceConfiguration;
        }

        private static void MetadataLoaded(object sender, ServiceMetadataLoadedEventArgs e)
        {
            LogonAsync();
        }

        private static async void LogonAsync()
        {
            await svcConfig.AuthenticateAsync(AuthCreds);
            var isvcConfig = svcConfig as IServiceConfiguration<IOrganizationService>;

            try
            {
                OrgServiceProxy = new OrganizationServiceProxy(isvcConfig, AuthCreds.SecurityTokenResponse);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            IsConnected = true;
            Connected();
        }
    }
}
